package cn.iotab.iotkit.mqtt.server.init;

import cn.iotab.iotkit.mqtt.server.config.MqttServerProperties;
import cn.iotab.iotkit.mqtt.server.config.TransportDriverProperties;
import cn.iotab.iotkit.transport.api.driver.TransportDriverConfig;
import cn.iotab.iotkit.transport.mqtt.MqttTransportServer;
import cn.iotab.iotkit.transport.mqtt.conf.MqttServerConfig;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.concurrent.atomic.AtomicBoolean;


@Component
@Slf4j
public class MqttServer {

    @Resource
    private MqttServerProperties mqttServerProperties;
    @Resource
    private TransportDriverProperties transportDriverProperties;

    private MqttTransportServer server;

    private final AtomicBoolean started = new AtomicBoolean(false);

    @PostConstruct
    @SneakyThrows
    public void init() {
        if (started.compareAndSet(false, true)) {
            MqttServerConfig config = mqttServerProperties;
            TransportDriverConfig transportDriverConfig = transportDriverProperties;
            server = new MqttTransportServer(config, transportDriverConfig);
            server.init();
            server.start();
        }
    }

    @PreDestroy
    public void destroy() {
        if (started.compareAndSet(true, false)) {
            if (server != null) {
                server.destroy();
            }
        }
    }
}
